package com.dayu.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dayu.common.constant.ProductConstant;
import com.dayu.common.to.SkuHasStockVo;
import com.dayu.common.to.SkuReductionTo;
import com.dayu.common.to.SpuBoundsTo;
import com.dayu.common.to.es.SkuEsModel;
import com.dayu.common.utils.PageUtils;
import com.dayu.common.utils.Query;
import com.dayu.common.utils.R;
import com.dayu.gulimall.product.dao.SpuInfoDao;
import com.dayu.gulimall.product.entity.*;
import com.dayu.gulimall.product.feign.CouponFeignService;
import com.dayu.gulimall.product.feign.SearchFeignClient;
import com.dayu.gulimall.product.feign.WareFeignClient;
import com.dayu.gulimall.product.service.*;
import com.dayu.gulimall.product.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private AttrService attrService;
    @Autowired
    private SpuInfoDescService descService;

    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private ProductAttrValueService attrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private WareFeignClient wareFeignClient;

    @Autowired
    private SearchFeignClient searchFeignClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 保存发布的商品
     *
     * @param vo
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveSpuVo(SpuSaveVo vo) {
        //1、    保存spu的基本信息 ;pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.baseMapper.insert(spuInfoEntity);

        //2、 保存spu描述信息; pms_spu_info_desc
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(spuInfoEntity.getId());
        List<String> decript = vo.getDecript();
        descEntity.setDecript(String.join(",", decript));
        descService.saveSpuDescInfo(descEntity);

        // 3、保存spu的图片信息; pms_spu_images
        List<String> images = vo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(), images);

        // 4、保存spu的规格参数; pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> attrValueEntityList = baseAttrs.stream().map(item -> {
            ProductAttrValueEntity productAttrValue = new ProductAttrValueEntity();
            productAttrValue.setAttrId(item.getAttrId());
            productAttrValue.setSpuId(spuInfoEntity.getId());
            AttrEntity attrEntity = attrService.getById(item.getAttrId());
            productAttrValue.setAttrName(attrEntity.getAttrName());
            productAttrValue.setQuickShow(item.getShowDesc());
            productAttrValue.setAttrValue(item.getAttrValues());
            return productAttrValue;
        }).collect(Collectors.toList());
        attrValueService.saveProductAttrValues(attrValueEntityList);

        Bounds bounds = vo.getBounds();
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        BeanUtils.copyProperties(bounds, spuBoundsTo);
        spuBoundsTo.setSpuId(spuInfoEntity.getId());
        R r1 = couponFeignService.saveSpuBounds(spuBoundsTo);
        if (r1.getCode() != 0) {
            log.error("保存商品积分信息失败");
        }

        // 5、 保存spu对应的sku信息
        List<Skus> skus = vo.getSkus();
        if (!CollectionUtils.isEmpty(skus)) {
            skus.forEach(item -> {
                String defaultImg = "";
                List<Images> imagesList = item.getImages();
                for (Images image : imagesList) {
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                    }
                }

                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
//                skuInfoEntity.setSkuDesc("");
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoEntity.setSkuName(spuInfoEntity.getSpuName());

                skuInfoService.saveSkuInfo(skuInfoEntity);

                Long skuId = skuInfoEntity.getSkuId();
                List<SkuImagesEntity> imagesEntityList = imagesList.stream().filter(i -> StringUtils.isNotEmpty(i.getImgUrl())).map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    return skuImagesEntity;
                }).collect(Collectors.toList());
                //保持sku的所有图片//5.3 保存sku的图片信息 pms_sku_images
                skuImagesService.saveBatch(imagesEntityList);

                //5.2 保存sku的销售属性信息 pms_sku_sale_attr_value
                List<Attr> attrs = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attrs.stream().map(attr -> {
                    SkuSaleAttrValueEntity saleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, saleAttrValueEntity);
                    saleAttrValueEntity.setSkuId(skuId);
                    return saleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                //5.4 保存sku的优惠、满减等信息；另一个库gulimall_sms-->sms_sku_ladder,sms_sku_full_reduction,sms_spu_bounds
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                //当设置了满减信息再调用远程服务
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1) {
                    R r = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r.getCode() != 0) {
                        log.error("保存sku满减优惠信息失败");
                    }
                }

            });
        }


        //


    }

    /**
     * 根据条件查询spu
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            wrapper.and(w -> {
                w.eq("id", key).or().like("spu_name", key);
            });
        }
        String brandId = (String) params.get("brandId");
        if (StringUtils.isNotEmpty(brandId) && Long.valueOf(brandId) != 0L) {
            wrapper.eq("brand_id", brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if (StringUtils.isNotEmpty(catelogId) && Long.valueOf(catelogId) != 0L) {
            wrapper.eq("catalog_id", catelogId);
        }
        String status = (String) params.get("status");
        if (StringUtils.isNotEmpty(status)) {
            wrapper.eq("publish_status", status);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 商品的上架
     *
     * @param spuId
     */
    @Override
    public void up(Long spuId) {
        // 1、查出当前spuId对应的所有sku信息，品牌的名字
        List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);
        List<Long> skuIds = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());

        // 查询当前sku所有可以被用来检索的属性
        List<ProductAttrValueEntity> baseAttrs = attrValueService.listForspu(spuId);
        List<Long> attrIds = baseAttrs.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        //查询可被检索的attrId
        List<Long> searchAttrIds = attrService.selectSearchAttrIds(attrIds);
        Set<Long> attrSet = new HashSet<>(searchAttrIds);
        List<SkuEsModel.Attrs> attrsList = baseAttrs.stream().filter(item -> attrSet.contains(item.getAttrId()))
                .map(item -> {
                    SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
                    BeanUtils.copyProperties(item, attrs);
                    return attrs;
                }).collect(Collectors.toList());

        Map<Long, Boolean> skuStockMap = null;

        try {
            // TODO 发送远程调用，库存系统查找库存 hasStock
            R r = wareFeignClient.hasStock(skuIds);
            //将获取到的数据转换成List，默认获取到的数据是Map格式
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {
            };
            skuStockMap = r.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        } catch (Exception e) {
            log.error("库存调用失败：e", e);
        }

        //2、封装信息
        Map<Long, Boolean> finalSkuStockMap = skuStockMap;
        List<SkuEsModel> esModels = skus.stream().map(item -> {
            //需要组装的es数据
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(item, skuEsModel);

            skuEsModel.setSkuPrice(item.getPrice());
            skuEsModel.setSkuImg(item.getSkuDefaultImg());

            skuEsModel.setHasStock((finalSkuStockMap == null) ? true : finalSkuStockMap.get(item.getSkuId()));
            // TODO  热度评分 0 默认上架0分，hotScore
            skuEsModel.setHotScore(0L);
            //
            BrandEntity brandEntity = brandService.getById(item.getBrandId());
            skuEsModel.setBrandImg(brandEntity.getLogo());
            skuEsModel.setBrandName(brandEntity.getName());

            CategoryEntity categoryEntity = categoryService.getById(skuEsModel.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());

            skuEsModel.setAttrs(attrsList);
            /**
             *     private Long hotScore;
             *     private String brandName;
             *     private String brandImg;
             *     private String catalogName;
             *
             */

            return skuEsModel;
        }).collect(Collectors.toList());

        // 将数据发送给es保存，gulimall-search

        R r = searchFeignClient.productStatusUp(esModels);
        if (r.getCode() == 0) {
            //上架成功
            //TODO 修改当前spu状态
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.PRODUCT_UP.getCode());
        } else {
            //上架失败
            //TODO 重复调用，接口幂等性，重试机制？

        }


    }

    @Override
    public SpuInfoEntity getBySkuId(Long skuId) {
        SkuInfoEntity skuInfoEntity = skuInfoService.getById(skuId);
        Long spuId = skuInfoEntity.getSpuId();
        SpuInfoEntity entity = getById(spuId);
        return entity;
    }

}